package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token){
        String s = stringRedisTemplate.opsForValue().get(token);
        return s;
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String url, Model model,@CookieValue(value = "sso_token",required = false) String token){
        if (!StringUtils.isEmpty(token)){
             return "redirect:"+url + "?token=" + token;
        }
        model.addAttribute("url",url);

        return "login";
    }

    @PostMapping("/doLogin")
    public String login(@RequestParam("username") String username,@RequestParam("password") String password,@RequestParam("url") String url,
            HttpServletResponse response){
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
            //登录成功跳转，跳转回之间的页面。
            String replace = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(replace,username);
            Cookie cookie = new Cookie("sso_token",replace);
            response.addCookie(cookie);
            return "redirect:"+url + "?token=" + replace;
        }else {
            return "login";
        }


    }
}
